<?php
/**
 * 前端用户账户信息服务
 * Created by PhpStorm.
 * User: 
 * Date: 
 * Time: 
 */

namespace app\services\controller;

use think\captcha\Captcha;
use think\Config;
use think\Db;
use think\Request;
use think\Response;
use weixin\weixin;
use app\model\UserBase;
use ethink\mvc\BaseController;
use ethink\acl\Auth;
use think\Loader;

class Cases extends BaseController
{
    public function __construct(Request $request = null)
    {
        $this->auth = new Auth(Config::get('api')['auth']);
        parent::__construct($request);
    }
 

    /**
     * [病例列表，自己所属的
     * 录入员：自己所属的
     * 初审员：自己处理过或者第一次提交待初审的
     * 终审员：自己处理过或者第一次提交待终审的
     * ]
     * @return [type] [description]
     */
    public function caselist(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("case-caselist,data:".json_encode($reqData));
            if(!is_array($reqData)){
                return $this->responseJson(null, $reqData);
            }            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $reqData['roleId'] = $user['session']['roleId'];
            //2查询数据
            $Model = new \app\services\model\CaseList();
            $reqData['pageSize'] = Config::get('api')['list']['page_size'];
            $list = $Model->caseList($userId,$reqData);
            $ret['data'] = $list->toArray();
            return $this->responseJson($ret, 0);                      
        }      
    }

    /**
     * [病例详情，自己所属的]
     * @return [type] [description]
     */
    public function casedetail(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("case-casedetail,data:".json_encode($reqData));
            if(!is_array($reqData)){
                return $this->responseJson(null, $reqData);
            }            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            // var_dump($user);exit;
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $reqData['roleId'] = $user['session']['roleId'];

            //2查询数据
            $Model = new \app\services\model\CaseList();
            $list = $Model->caseDetail($userId,$reqData); 
            return $this->responseJson($list, 0);                      
        }      
    }

    /**
     * [addAttachment 添加病例与附件的关联]
     * @return [type] [description]
     */
    public function addAttachment(){

         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $caseId = isset($_POST['caseId'])?$_POST['caseId']:"";
            if(!$caseId){
                return $this->responseJson(null, 1002);                  
            }
            // 4上传文件
            $upRet = $this->uploadFile('',1024000*20);//附件20m
            trace("addAttachment,upRet:".json_encode($upRet));
            // var_dump($upRet);exit;
            if($upRet['status']){
                return $this->responseJson(null, $upRet['status']);  

            }
            // $upRet['fileurl'] = "D:\wamphigh\www\csco/public/uploads/20181203/b25288ee37df4162695e497162f6565d.xlsx";
            // $upRet['dburl'] = "/uploads/20181203/b25288ee37df4162695e497162f6565d.xlsx";
            // $upRet['fileName'] = "李四的.xlsx";
            //5入库
            $Model = new \app\services\model\CaseList();
            $addData['fileName'] = $upRet['fileName']['name'];
            $addData['url'] = $upRet['dburl'];
            $addData['caseId'] = $caseId;
            $ret = $Model->addCaseAttachment($userId,$addData);
            return $this->responseJson(null, $ret);    
        }      
    }

    /**
     * [导入case例子]
     * @return [type] [description]
     */
    public function importCase(){
         if($this->request->isPost()){
            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3上传文件
            $upRet = $this->uploadFile('',1024000*5);//excel 5m
            trace("importCase,upRet:".json_encode($upRet));
            // var_dump($upRet);exit;
            if($upRet['status']){
                return $this->responseJson(null, $upRet['status']);  

            }
            // $upRet['fileurl'] = "D:\wamphigh\www\csco/public/uploads/20181203/b25288ee37df4162695e497162f6565d.xlsx";
            // $upRet['dburl'] = "/uploads/20181203/b25288ee37df4162695e497162f6565d.xlsx";
            // $upRet['fileName'] = "李四的.xlsx";
            // 4解析excel
            $retImport= $this->import_excel($upRet['fileurl']);
            if(!$retImport){
                return $this->responseJson(null, 3105);    
            }
            // var_dump($retImport['data'][0]);exit;
            //5入库
            $Model = new \app\services\model\CaseList();
            $addData['excelData'] = $retImport['data'];
            $addData['excelSheetCount'] = $retImport['sheetCount'];
            $addData['dburl'] = $upRet['dburl'];
            $addData['fileName'] = $upRet['fileName']['name'];
            $ret = $Model->addOneCase($userId,$addData);
            return $this->responseJson(null, $ret);    
        }      
    }



    /**
     * [uploadFile description]
     * @return [type] [description]
     */
    private function uploadFile($fileType='',$fileSize=1024000){
        trace("uploadFile,fileTypeArr:$fileType,filesize:$fileSize");
        // $file = request()->file('fileurl');
        $files = Request::instance()->file();
        if(null == $files){
            $ret['status']= 3104;
            return $ret;
        }
        foreach ($files as $key => $value) {
            # code...
            $file = $value;
            break;
        }
        // var_dump($file);exit;
        // if($file){
        // }
        // else{
        //     $ret['status']= 3104;
        //     return $ret;
        // }

        $checkArr = array();
        //2控制上传的文件类型，大小
        if($fileType){
            $checkArr['type'] = $fileType;           
        }

        if($fileSize){
            $checkArr['size'] = $fileSize;           
        }
        $retCheck = $file->check($checkArr);
        if(!$retCheck){
            trace("uploadFile,有误！");
            $ret['status']= 3102;
            return $ret; 
        }

        //文件上传
        $dbbase = Config::get('common.url_root') . 'uploads/';
        $filebase = ROOT_PATH . 'public' . DS . 'uploads/';
        
        /** @var $info \think\File */
        $info = $file->move($filebase);
        $ret['status']= 0;
        $ret['fileurl']= $filebase .$info->getSaveName();
        $ret['dburl']= $dbbase . $info->getSaveName();
        $ret['fileName'] = $info->getInfo();
        return $ret;     
    }

    public function sctonum($num, $double = 5){
        if(false !== stripos($num, "e")){
            $a = explode("e",strtolower($num));
            return bcmul($a[0], bcpow(10, $a[1], $double), $double);
        }
        else{
            return $num;
        }
    }
  


    /**
     * 导入excel文件
     * @param  string $file excel文件路径
     * @return array        excel文件内容数组
     */
    private function import_excel($file_path){
        // 判断文件是什么格式
        $type = pathinfo($file_path); 
        $type = strtolower($type["extension"]);
        $type=$type==='csv' ? $type : 'Excel5';
        ini_set('max_execution_time', '0');
        Vendor('phpexcel.Classes.PHPExcel.Reader.Excel2007');
        Vendor('phpexcel.Classes.PHPExcel.Reader.Excel5');
        Vendor('phpexcel.Classes.PHPExcel.Shared');
        // require("PHPExcel_Reader_Excel2007");
        if($type==='csv'){
            $PHPReader = new \PHPExcel_Reader_CSV();
              //默认字符集
            // $PHPReader->setInputEncoding('GBK');
  
            //默认分隔符  
            $PHPReader->setDelimiter(',');
  
        }
        else{
            $PHPReader = new \PHPExcel_Reader_Excel2007();
        }
        if (!$PHPReader->canRead($file_path)) {
            $PHPReader = new \PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($file_path)) {
                return false;
            }
        }
        // 判断使用哪种格式
        $objPHPExcel = $PHPReader->load($file_path); 
        $sheet = $objPHPExcel->getAllSheets(); 
        $sheetCount = $objPHPExcel->getSheetCount(); 
        $sheetName = $objPHPExcel->getSheetNames();
        // var_dump($sheetName);exit;
        $retData = array();
        foreach ($sheet as $key => $value) {
            // 取得总行数 
            $highestRow = $value->getHighestRow();     
            // 取得总列数      
            $highestColumn = $value->getHighestColumn(); 
            //循环读取excel文件,读取一条,插入一条
            $data=array();
            //从A列读取数据
            $p = 0;
            $objPHPExcel->setActiveSheetIndex($key);
            for($k='A';$k<=$highestColumn;$k++){
                //从第一行开始读取数据
                for($j=1;$j<=$highestRow;$j++){
                    // 读取单元格
                    $value = $objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue();
                    if($value){
                        if($j>1){
                            $data[$p][$j-1]=$this->sctonum($value,0);                            
                            $firstPos = strpos($data[$p][0],'日期');
                            $secondPos = strpos($data[$p][0],'时间');
                            if($firstPos===false && $secondPos===false){
                            }
                            else{   // echo $data[$p][$j-1];
                                if($type!=='csv'){
                                    $data[$p][$j-1]=gmdate('Y/m/d',\PHPExcel_Shared_Date::ExcelToPHP($data[$p][$j-1]));
                                }
                                else{
                                    //csv 直接就是字符串，无需转换
                                }
                            }
                        }
                        else{                            
                            $data[$p][$j-1]=$value;
                        }
                        // echo $data[$p][$j-1];exit;
                    }
                    else{
                        continue;
                    }
                }
                $p++;
            }  
             // var_dump($data);exit;
            $retData[$key]['sheet'] = $key;
            $retData[$key]['sheetName'] = isset($sheetName[$key])?$sheetName[$key]:"sheet".$key;
            $retData[$key]['data'] = $data;
        }
        $ret['sheetCount'] = $sheetCount;
        $ret['data'] = $retData;
        return $ret;
    }




    /**
     * [delAttachment 删除一个附件，只有录入员有权限]
     * @return [type] [description]
     */
    public function delAttachment(){
         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("delAttachment,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $reqData = $this->getJsonData(['caseId', 'attachmentId']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            $attachmentId = isset($reqData['attachmentId'])?$reqData['attachmentId']:"";
            if(!$caseId || !$attachmentId){
                return $this->responseJson(null, 1002);                  
            }
           
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            if(!empty($caseInfo['id'])){
                if($caseInfo['import_user_id']!=$userId){
                    return $this->responseJson(null, 3005);                  
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 删除关联
            $Model = new \app\services\model\CaseAttachment();
            $ret = $Model->deleteCaseAttachment($caseId,$attachmentId);
            trace("delAttachment,$ret");
            return $this->responseJson(null, 0);    
        }      
    }


    /**
     * [changeelement 更改病例的多个元素，只有录入员有权限]
     * @return [type] [description]
     */
    public function changeelement(){
         if($this->request->isPost()){
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("changeelement,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取
            $reqData = $this->getJsonData(['caseId', 'caseChange']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            $caseChange =isset($reqData['caseChange'])?$reqData['caseChange']:"";
            // var_dump($reqData);exit;
            if(!$caseId || !$caseChange){
                return $this->responseJson(null, 1002);                  
            }
           
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            if(!empty($caseInfo['id'])){
                if($caseInfo['import_user_id']!=$userId){
                    return $this->responseJson(null, 3005);                  
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 变更
            $Model = new \app\services\model\CaseChange();
            $ret = $Model->addOneChange($userId,$reqData);
            trace("changeelement,$ret");
            return $this->responseJson(null, $ret);    
        }      
    }





    /**
     * [deleteCase 删除一个病例，仅录入员有权限]
     * @return [type] [description]
     */
    public function deleteCase(){
         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("deleteCase,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $reqData = $this->getJsonData(['caseId']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            if(!$caseId ){
                return $this->responseJson(null, 1002);                  
            }
           
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            if(!empty($caseInfo['id'])){
                if($caseInfo['import_user_id']!=$userId){
                    return $this->responseJson(null, 3005);                  
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 删除病例
            $Model = new \app\services\model\CaseList();
            $ret = $Model->deleteCase($caseId);
            trace("deleteCase,$ret");
            return $this->responseJson(null, 0);    
        }      
    }



    /**
     * [导出case 病例]
     * @return [type] [description]
     */
    public function exportCase(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("exportCase");
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import','examine','final']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3导出文件，针对一个病例
            if(empty($reqData['caseId'])){
                return $this->responseJson(null, 1002); 
            }
            //4查询详情           
            $Model = new \app\services\model\CaseList();
            $caseBaseInfo = $Model->caseBaseDetail($userId,$reqData); 
            if(!$caseBaseInfo){
                return $this->responseJson(null, 1002); 
            }
            $caseTitle = $caseBaseInfo['title'];

            $elementList = $Model->elementDetail($reqData['caseId']); 
            if(!$elementList){
                return $this->responseJson(null, 3006); 
            }

            // 4生成excel
            $operateElement = array();
            $tempSheet = array();
            $tempSheet['data'] = array();

            foreach ($elementList as $key => $value) {
                // var_dump($value);
                $e_key = $value['key'];
                $e_value = $value['value'];
                $e_sheet = $value['sheet'];
                $e_sheet_name = $value['sheetName'];
                if($key==0){
                    $tempSheet['sheetName'] = $e_sheet_name;
                    $tempSheet['sheet'] = $e_sheet;
                    $temp['key'] = $e_key;
                    $temp['value'] = $e_value;
                    array_push($tempSheet['data'],$temp);
                }
                else{
                    if($tempSheet['sheet']==$value['sheet']){                            
                        $temp['key'] = $e_key;
                        $temp['value'] = $e_value;
                        array_push($tempSheet['data'],$temp);
                    }
                    else{
                        array_push($operateElement,$tempSheet);
                        $tempSheet['sheetName'] = $e_sheet_name;
                        $tempSheet['sheet'] = $e_sheet;
                        $tempSheet['data'] = array();
                        $temp['key'] = $e_key;
                        $temp['value'] = $e_value;
                        array_push($tempSheet['data'],$temp);
                    }   
                }
            }
            if($tempSheet){
                array_push($operateElement,$tempSheet);                
            }
            // var_dump($operateElement);exit;
            //7导出
            $retImport= $this->export_excel($caseTitle,$operateElement);

            if($retImport['status']){
                return $this->responseJson(null, 3105);    
            }
            $ret['out_data']['fileurl'] = $retImport['fileurl'];
            return $this->responseJson($ret, 0);    
        }      
    }


     /**
     * 导出excel文件
     * @param  string $file excel文件路径
     * @return array        excel文件内容数组
     */
    private function export_excel($caseTitle,$elementList){
        header("Content-type: text/html; charset=utf-8");
        ini_set('max_execution_time', '0');
        vendor("phpexcel.Classes.PHPExcel");
        vendor("phpexcel.Classes.PHPExcel.Writer.IWriter");
        vendor("phpexcel.Classes.PHPExcel.Writer.Abstract");
        vendor("phpexcel.Classes.PHPExcel.Writer.Excel5");
        vendor("phpexcel.Classes.PHPExcel.Writer.Excel2007");
        vendor("phpexcel.Classes.PHPExcel.IOFactory");
        $objPHPExcel = new \PHPExcel();
        // $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        foreach ($elementList as $key => $value) {

            $data = $value['data'];
            if($data&&$value['sheetName']){
                if($key>0){
                    $objPHPExcel->createSheet($key);
                }
                $objPHPExcel->setActiveSheetIndex($key);                   //设置sheet的起始位置
                $objPHPExcel->getActiveSheet()->setTitle($value['sheetName']);      //设置sheet的名称
                // 设置表头信息
                $asc = "A";
                foreach ($data as $key1 => $value1) {
                    // echo $asc;
                    # code...
                    if($key1<100){
                        $objPHPExcel->getActiveSheet()->setCellValue($asc.'1', $value1['key']);
                        $objPHPExcel->getActiveSheet()->setCellValue($asc.'2' ,$value1['value']);   
                    }
                    else{
                        break;
                    }
                    $asc++;
                }
            }
            // break;
        }
        // exit;
        /*--------------下面是设置其他信息------------------*/
        // $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');   //通过PHPExcel_IOFactory的写函数将上面数据写出来
        
        $PHPWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel,"Excel2007");
            
        //创建Excel输出对象   
        $subPath = 'uploads/export/'.date("Y-m-d");
        $filebase = ROOT_PATH . 'public' . DS .$subPath;
        $this->mk_dir($filebase);
        $fileNameArr = explode(".", $caseTitle);
        $fileType = $fileNameArr[count($fileNameArr)-1];
        if($fileType=="csv" ||$fileType=="xls"||$fileType=="xlsx"){
            $filename = "/$caseTitle";
        }
        else{
            $filename = "/$caseTitle.xlsx";
        }
        $fileFull = $filebase.$filename;    
        // $fileFull = $filebase.mb_convert_encoding($filename, 'UTF-8', 'gbk'); 
        
        ob_end_clean();//清除缓冲区,避免乱码

        // $PHPWriter->save( mb_convert_encoding($fileFull, 'gbk', 'UTF-8') );   
        $PHPWriter->save(  $fileFull );
        $ret['status'] = 0;
        $ret['fileurl'] =Config::get('common.url_root') . $subPath . $filename;
        return $ret;
    }
    /**
     * [mk_dir description]
     * @param  [type]  $dir [description]
     * @param  integer $mod [description]
     * @return [type]       [description]
     */
    private function mk_dir($dir, $mod = 0777){
        $path_complete =$dir;
        if(!file_exists($path_complete)){ //file_exists检测目录或文件是否存在
            mkdir($path_complete,$mod,true);
        }
        return true;
    }



    /**
     * [submitCase 提交审核一个病例，仅录入员有权限]
     * @return [type] [description]
     */
    public function submitCase(){
         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("submitCase,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['import']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $reqData = $this->getJsonData(['caseId']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            if(!$caseId ){
                return $this->responseJson(null, 1002);                  
            }
           
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            if(!empty($caseInfo['id'])){
                if($caseInfo['import_user_id']!=$userId){
                    return $this->responseJson(null, 3005);                  
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 提交审核一个病例(只有录入员有权限)
            $Model = new \app\services\model\CaseList();
            $reqData['lastStatus'] = [0,1];
            $ret = $Model->submitCase($userId,$caseId,'录入员',2,$reqData);
            trace("submitCase,$ret");
            return $this->responseJson(null, $ret );    
        }      
    }


    /**
     * [submitQuestion 针对一个病例发起质疑，
     *     初审员有权限，且是自己的，或者初审员员为空，通过发起质疑，归类到自己名下
     *     终审员有权限，且是自己的，或者终审员为空，通过发起质疑，归类到自己名下
     * ]
     *         
     * @return [type] [description]
     */
    public function submitQuestion(){
         if($this->request->isPost()){
            //1校验登陆状态
            $user = $this->checkUserStatus();
            if($user['status']){
                return $this->responseJson(null, $user['status']);
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            // 3获取文件id
            $reqData = $this->getJsonData(['caseId','questionData','roleStatus']);
            if(!is_array($reqData)){
                return $this->responseJson(null, 1002);                
            }

            trace("submitQuestion,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            if($reqData['roleStatus'] == 2){
                //初审员
                $import = $this->checkCaseRole($roleId,['examine']);
                if($import){
                    return $this->responseJson(null, $import);   
                }
                else{
                    $reqData['roleString'] = $roleString = "examine";//
                    $roleStringName = "初审员";//
                    $reqData['newStatus'] = 1; //有质疑，审核失败
                    $reqData['lastStatus'] = 2;
                    $reqData['newLogStatus'] = 6; 
                }
            }
            else{
                //终审员
                $import = $this->checkCaseRole($roleId,['final']);
                if($import){
                    return $this->responseJson(null, $import);    
                }
                else{
                    $reqData['roleString'] = $roleString = "final";//终审员
                    $roleStringName = "终审员";//
                    $reqData['newStatus'] = 1; //有质疑，审核失败
                    $reqData['lastStatus'] = 3;
                    $reqData['newLogStatus'] = 7;  
                }
                
            }

            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            if(!$caseId ){
                return $this->responseJson(null, 1002);                  
            }
           
            //4是不是自己的case
            $reqData['newCase'] = 0;
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            // var_dump($caseInfo);exit;
            if(!empty($caseInfo['id'])){ 
                if($roleString=='examine'){
                    if($caseInfo['examine_user_id']){
                        if($caseInfo['examine_user_id']!=$userId){
                            return $this->responseJson(null, 3005);                  
                        }
                        else{
                            //自己的
                        }
                    }
                    else{
                        if($caseInfo['status']!=2){
                            return $this->responseJson(null, 3011);
                        }
                        else{
                            //录入员新提
                            $reqData['newCase'] = 1;
                            
                        }
                    }

                }
                else{ 
                    if($caseInfo['final_user_id']){
                        if($caseInfo['final_user_id']!=$userId){
                            return $this->responseJson(null, 3005);                  
                        }
                        else{
                            //自己的
                        }
                    }
                    else{
                        if($caseInfo['status']!=3){
                            return $this->responseJson(null, 3011);
                        }
                        else{
                            //录入员新提
                            $reqData['newCase'] = 1;
                            
                        }
                    }
                }

            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 提交病例的质疑(只有初审员/终审员有权限)
            $Model = new \app\services\model\CaseList();
            $ret = $Model->submitQuestion($userId,$caseId,$roleStringName,$reqData);
            trace("submitQuestion,$ret");
            return $this->responseJson(null, 0);    
        }      
    }


     /**
     * [所有的变更记录]
     * @return [type] [description]
     */
    public function changeLog(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("case-changeLog,data:".json_encode($reqData));
            if(!is_array($reqData)){
                return $this->responseJson(null, $reqData);
            }            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            // var_dump($user);exit;
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $reqData['roleId'] = $user['session']['roleId'];
            if(empty($reqData['caseId'])){
                return $this->responseJson(null, 1002);  
            }
            //4查询所有的属性，方便页面排版
            $retArr = array();
            $elementArr = array();
            $operateElement['data'] = array();
            $Model = new \app\services\model\CaseList();
            $baseInfo = $Model->caseBaseDetail($userId,$reqData);
            if(!$baseInfo){
                return $this->responseJson(null, 1002);                 
            }
            $firstCreateTime = $baseInfo['create_time'];
            $changeList = $Model->elementChange($reqData['caseId']);
            if(!$changeList){
                return $this->responseJson(null, 3012);                 
            }
            $allList = $Model->elementDetail($reqData['caseId']); 
            $firstChangeList = $Model->elementFirstChange($reqData['caseId']); 
            // print_r($changeList);
            // print_r($allList);exit;
            foreach ($changeList as $key => $value) {
                foreach ($firstChangeList as $key2 => $value2) {
                    if($value['qColumn']==$value2['q_column']){
                        $operateElement['addTime'] = $firstCreateTime;
                        $temp=array(
                            "id"   => 0,
                            "before"   => '', //第一次默认为空
                            "after"   => $value2['before'],
                            "qColumn"   => $value['qColumn'],
                            "addTime" =>$firstCreateTime
                        );
                        array_push($operateElement['data'],$temp);
                        break;
                    }
                }
            }
            array_push($retArr,$operateElement);     
            // print_r($retArr);exit;

            $ret['out_data']["element"] = $allList;
            $ret['out_data']["changeElement"] = $changeList;
            // print_r($retArr);exit;
            // var_dump($operateElement);exit;
            $operateElement = array();
            $operateElement['data'] = array();
            //2查询数据
            $list = $Model->changeLog($userId,$reqData); 
            // print_r($list);exit;
            foreach ($list as $key => $value) {
                if($key==0){
                    $operateElement['addTime'] = $value['addTime'];
                    $temp=array(
                        "id"   => $value['id'],
                        "before"   => $value['before'],
                        "after"   => $value['after'],
                        "qColumn"   => $value['qColumn'],
                        "addTime" =>$value['addTime']
                    );
                    array_push($operateElement['data'],$temp);
                }
                else{
                    if($operateElement['addTime'] == $value['addTime']){
                        $temp=array(
                            "id"   => $value['id'],
                            "before"   => $value['before'],
                            "after"   => $value['after'],
                            "qColumn"   => $value['qColumn'],
                            "addTime" =>$value['addTime']
                        );
                        array_push($operateElement['data'],$temp);                        
                    }
                    else{
                        $this->complementData($retArr[0],$operateElement);
                        array_push($retArr,$operateElement);
                        // print_r($retArr);exit;
                        $operateElement['addTime'] = $value['addTime'];
                        $operateElement['data'] = array();
                        $temp=array(
                            "id"   => $value['id'],
                            "before"   => $value['before'],
                            "after"   => $value['after'],
                            "qColumn"   => $value['qColumn'],
                            "addTime" =>$value['addTime']
                        );
                        array_push($operateElement['data'],$temp);  
                    }
                }
            }

             
            if($operateElement){
                $this->complementData($retArr[0],$operateElement);
                array_push($retArr,$operateElement);                
            }
            //重新排序
            // $retArrOk = array();
            // foreach ($retArr as $key => $value) {
            //     if($key==0){
            //         array_push($retArrOk,$value);
            //     }
            //     else{
            //         $temp['addTime'] = $value['addTime'];
            //         $temp['data'] = array();
            //         foreach ($retArrOk[0]['data'] as $d_key => $d_value) {
            //             foreach ($value['data'] as $d_key2 => $d_value2) {
            //                 if($d_value['qColumn'] == $d_value2['qColumn']){
            //                     array_push($)
            //                     break;
            //                 }
            //             }
            //         }
            //     }
            // }
            foreach ($retArr as $key => $value) {
                $tempData = $value['data'];
                // var_dump($tempData);
                usort($tempData,"self::sortData");
                // var_dump($tempData);
                $retArr[$key]['data']= $tempData;
            }
            // exit;
            $ret['data'] = $retArr;
            return $this->responseJson($ret, 0);                       
        }      
    }
    /**
     * [sortData 重新排序]
     * @return [type] [description]
     */
    public static function sortData($a,$b){
        // var_dump($a);
        // var_dump($b);
        if($a['qColumn']>=$b['qColumn']){
            // echo 1;
            return 1;
        }
        else{
            // echo -1;
            return -1;
        }
    }
    /**
     * 补全数组
     */
    private function complementData($allElem,&$changeElem){
        // var_dump($allElem);
        // var_dump($changeElem);
        foreach ($allElem['data'] as $key => $value) {
            $mark = 0;
            foreach ($changeElem['data'] as $key2 => $value2) {
                if($value['qColumn']==$value2['qColumn']){
                    $mark=1;
                    break;
                }
            }

            if($mark==0){
                // var_dump($value);exit;
                //缺少字段，补全  经过1226讨论，不用补全
                // array_push($changeElem['data'],$value);
            }
        }
        // var_dump($changeElem);exit;
    }


    /**
     * [submitFinal 初审通过一个病例，仅初审员有权限]
     * @return [type] [description]
     */
    public function submitFinal(){
         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("submitFinal,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['examine']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $reqData = $this->getJsonData(['caseId']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            if(!$caseId ){
                return $this->responseJson(null, 1002);                  
            }
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            $reqData['newCase'] = 0;
            if(!empty($caseInfo['id'])){
                if($caseInfo['examine_user_id']){
                    if($caseInfo['examine_user_id']!=$userId){
                        return $this->responseJson(null, 3005);                  
                    }
                    else{
                        //自己的
                    }
                }
                else{
                    if($caseInfo['status']!=2){

                    }
                    else{
                        //new
                        $reqData['newCase'] = 1;
                    }
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 初审通过
            $Model = new \app\services\model\CaseList();
            $reqData['lastStatus'] = [2];
            $ret = $Model->submitCase($userId,$caseId,'初审员',3,$reqData);
            trace("submitFinal,$ret");
            return $this->responseJson(null, $ret);    
        }      
    }
      

    /**
     * [submitSuccess 终审通过一个病例，仅终审员有权限]
     * @return [type] [description]
     */
    public function submitSuccess(){
         if($this->request->isPost()){            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $roleId = $user['session']['roleId'];

            trace("submitSuccess,userId:$userId,roleId:$roleId");
            //2查询用户角色对应的case权限
            $import = $this->checkCaseRole($roleId,['final']);
            if($import){
                return $this->responseJson(null, $import);    
            }
            // 3获取文件id
            $reqData = $this->getJsonData(['caseId']);
            $caseId = isset($reqData['caseId'])?$reqData['caseId']:"";
            if(!$caseId ){
                return $this->responseJson(null, 1002);                  
            }
            //4是不是自己的case
            $Model = new \app\services\model\CaseList();
            $caseInfo = $Model->queryCaseId($caseId); 
            $reqData['newCase'] = 0;
            if(!empty($caseInfo['id'])){
                if($caseInfo['final_user_id']){
                    if($caseInfo['final_user_id']!=$userId){
                        return $this->responseJson(null, 3005);                  
                    }
                    else{
                        //自己的
                    }
                }
                else{
                    if($caseInfo['status']!=3){

                    }
                    else{
                        //new
                        $reqData['newCase'] = 1;
                    }
                }
            }
            else{
                return $this->responseJson(null, 3004);                  
            }

            //5 终审通过
            $Model = new \app\services\model\CaseList();
            $reqData['lastStatus'] = [3];
            $ret = $Model->submitCase($userId,$caseId,'终审员',4,$reqData);
            trace("submitSuccess,$ret");
            return $this->responseJson(null, $ret);    
        }      
    }


     /**
     * [病例列表，所有的，仅返回id，名字，过滤，前10个,只返回审核通过的]
     * @return [type] [description]
     */
    public function caseBaseList(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("case-caseBaseList,data:".json_encode($reqData));
            if(!is_array($reqData)){
                return $this->responseJson(null, $reqData);
            }            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            $reqData['roleId'] = $user['session']['roleId'];
            //2查询数据
            $Model = new \app\services\model\CaseList();
            $reqData['pageSize'] = Config::get('api')['list']['page_size'];
            $reqData['status'] =4;
            $list = $Model->caseBaseList($userId,$reqData);
            $ret['data'] = $list->toArray();
            return $this->responseJson($ret, 0);                      
        }      
    }


     /**
     * [消息列表 ]
     * @return [type] [description]
     */
    public function noticeList(){
         if($this->request->isGet()){
            $reqData = $this->request->get();
            trace("case-caselist,data:".json_encode($reqData));
            if(!is_array($reqData)){
                return $this->responseJson(null, $reqData);
            }            
            //1校验登陆状态
            $user = $this->checkUserStatus();  
            if($user['status']){
                return $this->responseJson(null, $user['status']);                
            }
            $userId = $user['session']['userId'];
            // $reqData['roleId'] = $user['session']['roleId'];
            //2查询数据
            $Model = new \app\services\model\Notice();
            $reqData['pageSize'] = Config::get('api')['list']['page_size'];
            $list = $Model->noticeList($userId,$reqData);
            $ret['data'] = $list->toArray();
            return $this->responseJson($ret, 0);                      
        }      
    }
      
}